import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'dart:io';

import 'index.dart';

class ChatPage extends GetView<ChatController> {
  const ChatPage({super.key});

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        // 背景
        Positioned.fill(child: Image.asset(Images.startBg, fit: BoxFit.cover)),

        // 聊天内容
        Column(
          children: [
            // 顶部安全区域
            SizedBox(height: MediaQuery.of(Get.context!).padding.top),

            // AppBar高度补偿
            SizedBox(height: kToolbarHeight),

            // 头像区域（单聊和群聊都显示）
            _buildChatHeader(),

            // 分割线
            Container(
              height: 1,
              color: Colors.white.withOpacity(0.2),
              margin: EdgeInsets.symmetric(vertical: 10.h),
            ),

            // 聊天消息列表
            Expanded(child: _buildMessageList()),
          ],
        ),
      ],
    );
  }

  // 构建聊天头部区域（包括头像）
  Widget _buildChatHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
      child: Obx(() {
        if (controller.isGroupChat.value) {
          // 群聊头像
          return _buildGroupAvatars();
        } else {
          // 单聊头像（两个用户）
          return _buildPrivateChatAvatars();
        }
      }),
    );
  }

  // 构建单聊头像（显示两个用户的头像）
  Widget _buildPrivateChatAvatars() {
    final userService = Get.find<UserService>();

    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 当前用户头像
            Container(
              width: 60.w,
              height: 60.h,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2.w),
              ),
              child: ClipOval(
                child:
                    userService.currentUser.value != null
                        ? _buildUserAvatar(userService.currentUser.value!)
                        : Image.asset(Images.avatar1, fit: BoxFit.cover),
              ),
            ),

            // 中间图标
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15.w),
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: Color(0xFF5490EE),
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.chat, color: Colors.white, size: 20.sp),
            ),

            // 聊天对象头像
            Container(
              width: 60.w,
              height: 60.h,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2.w),
              ),
              child: ClipOval(
                child:
                    controller.chatTarget.value != null
                        ? _buildUserAvatar(controller.chatTarget.value!)
                        : Image.asset(Images.avatar1, fit: BoxFit.cover),
              ),
            ),
          ],
        ),
      ],
    );
  }

  // 构建群聊头像（参考share页面）
  Widget _buildGroupAvatars() {
    return Column(
      children: [
        SizedBox(
          height: 80.h,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 群聊头像组
              SizedBox(
                width: 80.w,
                height: 80.h,
                child: Stack(
                  children: [
                    // 左上角头像
                    _buildGroupAvatarPosition(0, Offset(0, 0)),
                    // 右上角头像
                    _buildGroupAvatarPosition(1, Offset(40.w, 0)),
                    // 左下角头像
                    _buildGroupAvatarPosition(2, Offset(0, 40.h)),

                    // 中间的图标
                    Positioned(
                      left: 30.w,
                      top: 30.h,
                      child: Container(
                        width: 20.w,
                        height: 20.h,
                        decoration: BoxDecoration(
                          color: Color(0xFF5490EE),
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                          child: Icon(
                            Icons.group,
                            size: 12.sp,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),

                    // 右下角显示剩余人数或第四个头像
                    controller.groupMembers.length > 4
                        ? Positioned(
                          right: 0,
                          bottom: 0,
                          child: Container(
                            width: 40.w,
                            height: 40.h,
                            decoration: BoxDecoration(
                              color: const Color(0xFF4169B8),
                              shape: BoxShape.circle,
                              border: Border.all(color: Colors.white, width: 2),
                            ),
                            child: Center(
                              child: Text(
                                '+${controller.groupMembers.length - 3}',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12.sp,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                          ),
                        )
                        : _buildGroupAvatarPosition(3, Offset(40.w, 40.h)),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 构建群聊中的单个头像位置
  Widget _buildGroupAvatarPosition(int index, Offset offset) {
    if (index < controller.groupMembers.length) {
      return Positioned(
        left: offset.dx,
        top: offset.dy,
        child: Container(
          width: 40.w,
          height: 40.h,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(color: Colors.white, width: 2),
          ),
          child: ClipOval(
            child: _buildUserAvatar(controller.groupMembers[index]),
          ),
        ),
      );
    } else {
      return SizedBox();
    }
  }

  // 构建用户头像
  Widget _buildUserAvatar(User user) {
    return user.avatar != null && user.avatar!.isNotEmpty
        ? (user.avatar!.startsWith('assets/')
            ? Image.asset(user.avatar!, fit: BoxFit.cover)
            : Image.file(
              File(user.avatar!),
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Image.asset(Images.avatar1, fit: BoxFit.cover);
              },
            ))
        : Image.asset(Images.avatar1, fit: BoxFit.cover);
  }

  // 构建聊天消息列表
  Widget _buildMessageList() {
    return Obx(() {
      if (controller.isLoading.value) {
        return Center(child: CircularProgressIndicator(color: Colors.white));
      }

      if (controller.messages.isEmpty) {
        return Center(
          child: Text(
            'No messages yet',
            style: TextStyle(color: Colors.white70, fontSize: 16.sp),
          ),
        );
      }

      return ListView.builder(
        controller: controller.scrollController,
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
        itemCount: controller.messages.length,
        itemBuilder: (context, index) {
          final message = controller.messages[index];
          final isCurrentUser = controller.isMessageFromCurrentUser(message);
          final sender = controller.getMessageSender(message);

          return _buildMessageItem(message, isCurrentUser, sender);
        },
      );
    });
  }

  // 构建单条消息项
  Widget _buildMessageItem(
    ChatMessage message,
    bool isCurrentUser,
    User? sender,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 发送者头像 (只在非当前用户消息时显示)
          if (!isCurrentUser)
            Container(
              width: 40.w,
              height: 40.h,
              margin: EdgeInsets.only(right: 10.w),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 1.w),
              ),
              child: ClipOval(
                child:
                    sender != null
                        ? _buildUserAvatar(sender)
                        : Image.asset(Images.avatar1),
              ),
            ),

          // 消息内容
          Flexible(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: isCurrentUser ? Colors.white : Color(0xFF3C6DB5),
                borderRadius: BorderRadius.only(
                  topLeft:
                      isCurrentUser
                          ? Radius.circular(20.r)
                          : Radius.circular(0.r),
                  topRight:
                      isCurrentUser
                          ? Radius.circular(0.r)
                          : Radius.circular(20.r),
                  bottomLeft: Radius.circular(20.r),
                  bottomRight: Radius.circular(20.r),
                ),
              ),
              child: Text(
                message.content,
                style: TextStyle(
                  color: isCurrentUser ? Colors.black : Colors.white,
                  fontSize: 14.sp,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),

          // 当前用户头像 (只在当前用户消息时显示)
          if (isCurrentUser)
            Container(
              width: 40.w,
              height: 40.h,
              margin: EdgeInsets.only(left: 10.w),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 1.w),
              ),
              child: ClipOval(
                child:
                    sender != null
                        ? _buildUserAvatar(sender)
                        : Image.asset(Images.avatar1),
              ),
            ),
        ],
      ),
    );
  }

  // 构建输入区域
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.only(top: 2.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.r),
          topRight: Radius.circular(30.r),
        ),
      ),
      child: SafeArea(
        child: Container(
          padding: EdgeInsets.only(
            left: 20.w,
            right: 20.w,
            top: 24.h,
            bottom: 36.h,
          ),
          decoration: BoxDecoration(
            color: const Color(0xFF08306F),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(28.r),
              topRight: Radius.circular(28.r),
            ),
          ),
          child: Row(
            children: [
              // 评论输入框
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.51),
                    borderRadius: BorderRadius.circular(26.r),
                  ),
                  child: TextField(
                    controller: controller.messageController,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w400,
                    ),
                    decoration: InputDecoration(
                      hintText: 'Say something...',
                      hintStyle: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w400,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 10.h),
                    ),
                  ),
                ),
              ),

              // 发送按钮
              SizedBox(width: 8.w),
              InkWell(
                onTap: () {
                  if (controller.messageController.text.trim().isNotEmpty) {
                    controller.sendMessage();
                  }
                },
                child: Container(
                  width: 96.w,
                  height: 52.h,
                  decoration: ShapeDecoration(
                    color: Colors.white.withValues(alpha: 0.51),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(26.r),
                    ),
                  ),
                  child: Center(
                    child: Text(
                      'Send',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 17.sp,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChatController>(
      init: ChatController(),
      id: "chat",
      builder: (_) {
        return Scaffold(
          extendBodyBehindAppBar: true,
          backgroundColor: const Color(0xFF0F3876),
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            centerTitle: true,
            title: Obx(
              () => Text(
                controller.chatTitle.value,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
            leading: IconButton(
              icon: Icon(IconFontIcons.iconBack, color: Colors.white),
              onPressed: () => Get.back(),
            ),
            actions: [
              // 根据聊天类型显示不同的按钮
              Obx(
                () =>
                    controller.isGroupChat.value
                        ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            // 举报按钮
                            IconButton(
                              icon: Icon(
                                IconFontIcons.iconReport,
                                color: Colors.white,
                              ),
                              onPressed: () {
                                controller.reportGroup();
                              },
                            ),
                          ],
                        )
                        : IconButton(
                          icon: Icon(
                            IconFontIcons.iconReport,
                            color: Colors.white,
                          ),
                          onPressed: () {
                            controller.reportUser();
                          },
                        ),
              ),
            ],
            systemOverlayStyle: SystemUiOverlayStyle.light,
          ),
          body: SafeArea(top: false, bottom: false, child: _buildView()),
          bottomSheet: _buildInputArea(),
        );
      },
    );
  }
}
